package com.example.myapplication.RoomFile

import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.myapplication.R

class RoomActivity() : AppCompatActivity(), View.OnClickListener {

    lateinit var textView: TextView
    lateinit var viewModel: WordViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room)

        viewModel = ViewModelProvider(this)[WordViewModel::class.java]
        viewModel.data.observe(this,object: Observer<List<Word>>{
            override fun onChanged(value: List<Word>) {
                var stringB: StringBuilder = StringBuilder()
                for (word in value){
                    stringB.append(word.id)
                    stringB.append(" ")
                    stringB.append(word.word)
                    stringB.append("--")
                    stringB.append(word.chineseMeaning)
                    stringB.append("\n")
                }
                textView.text = stringB.toString()
            }
        })
        textView = findViewById<TextView>(R.id.textView22)
        val insertBtn = findViewById<Button>(R.id.button23)
        val updateBtn = findViewById<Button>(R.id.button24)
        val clearBtn = findViewById<Button>(R.id.button25)
        val deleteBtn = findViewById<Button>(R.id.button26)
        insertBtn.setOnClickListener(this)
        updateBtn.setOnClickListener(this)
        clearBtn.setOnClickListener(this)
        deleteBtn.setOnClickListener(this)
    }
    override fun onClick(v: View?) {
        v?.let {
            when(it.id){
                //insert
                R.id.button23 ->{
                    val word = Word("Hello", "你好,")
                    val word2 = Word("world", "世界!")
                    viewModel.insertWords(word,word2)
                }
                R.id.button24 ->{
                    val word = Word("good", "很好")
                    word.id = 1
                    viewModel.updateWords(word)
                }
                R.id.button25 ->{
                    viewModel.deleteAll()
                }
                R.id.button26 ->{
                    val word:Word = Word("good", "很好")
                    word.id = 2
                    val word2:Word = Word("good", "很好")
                    word2.id = 3
                    viewModel.deleteWords(word,word2)
                }

            }
        }
    }
}